<template>
    <div>
        <div id="map"></div>
        <!-- 地图控件 -->
    </div>
</template>
<script lang='ts' setup>
import { onMounted, defineModel } from 'vue'
import {
    // RasterLayer, 
    Popup,
    // LayerPopup,
    PointLayer,
    Scene,
    LineLayer,
    // PolygonLayer,
    // Popup,
    // IPopupOption
} from '@antv/l7';
import { DrawCircle, DrawLine } from '@antv/l7-draw';
import {
    // Map, 
    GaodeMap
} from '@antv/l7-maps';
(window as any)._AMapSecurityConfig = { securityJsCode: "31f61184d0ec34eecaf52316bdb3f236" }
// import { number } from 'echarts';
// import { last } from 'lodash';
// import { map } from 'lodash';
// import { color } from 'echarts';
// import dayjs from 'dayjs';
// *侦测范围
// import { circleList } from './mock';
const scene = ref();
const local = useLocal()
const temp = useTemp()
// const rasterLayer2 = ref()
// const rasterLayer3 = ref()
const mapType = defineModel('mapType', { default: 'satellite' })
const planeList = defineModel('planeList', { default: [] })
const boatList = defineModel('boatList', { default: [] })
const spectList = defineModel('spectList', { default: [] })
const trackList = defineModel('trackList', { default: [] })
const deviceList = defineModel('deviceList', { default: [] })
const deviceSn = defineModel('deviceSn', { default: '' })
// *管理区域列表
const controlAreaList = defineModel('controlAreaList', { default: [] })
const spectPointLayer = ref()
const planePointLayer = ref()
const boatPointLayer = ref()
// const track = ref()
const trackPointLayer = ref()
const trackPointSpaceLayer = ref()
const operatorPointLayer = ref()
const correlationPointLayer = ref()
const deviceLayer = ref()
const controlAreaLayer = ref()
const controlAreaLayer2 = ref()
const deviceRangeLayer = ref()
const deviceScanLayer = ref()
const mounted = ref(false)
const lastScanPosition = ref([])
const deviceRangeRadius = ref()
const deviceScanStatus = ref()
const storedDeviceId = ref()
// const operatorPointLayer = ref()
// const spectPointLayer = ref()
// 卫星地图
// const createSatelliteMap = () => {
//     const url1 =
//         'https://webst0{1-3}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}';
//     const url2 =
//         'https://webst0{1-2}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}';
//     //地图
//     rasterLayer2.value = new RasterLayer({
//         zIndex: 0,
//     }).source(url1, {
//         parser: {
//             type: 'rasterTile',
//             tileSize: 256,
//             zoomOffset: 1,
//         },
//     });

//     //地图
//     rasterLayer3.value = new RasterLayer({
//         zIndex: 0,
//     }).source(url2, {
//         parser: {
//             type: 'rasterTile',
//             tileSize: 256,
//             zoomOffset: 1,
//         },
//     });
//     scene.value.addLayer(rasterLayer2.value);
//     scene.value.addLayer(rasterLayer3.value);
// }
// 地图部分
const init = () => {
    // if (mapType.value == 'satellite') {
    //     scene.value = new Scene({
    //         id: 'map',
    //         map: new Map({
    //             center: [120.52, 30.40],
    //             // zoom: 15.5,
    //             zoom: 15,
    //             style: 'normal',
    //             // token: '77cc78c37d8b5425cd4d0f2fa76ded69',
    //             token: 'f6e6a050f46df0798a05b7ceed50a817',
    //             maxZoom: 18,
    //         })
    //     });
    // } else {
    let arr = (deviceList.value as any)?.[0]?.point?.split(',')?.map((item: any) => Number(item))
    scene.value = new Scene({
        id: 'map',
        map: new GaodeMap({
            // center: arr || arr[0],
            center: arr || [121.245800, 31.394559],
            zoom: 15,
            style: 'dark',
            // pitch:90,s
            // token: local.mapKey.aMap,
            token: 'a9990a040ddd05561ff172263e667341',
            plugin: ['AMap.Weather', 'AMap.CitySearch', 'AMap.Geocoder']
        }),
    });
    // }
    scene.value.addImage(
        '00',
        '/Group584.svg',
    );
    scene.value.addImage(
        '01',
        '/pilot.svg',
    );
    scene.value.addImage(
        '02',
        '/spect.svg',
    );
    scene.value.addImage(
        '03',
        '/fiveGA.svg',
    );
    scene.value.addImage(
        '04',
        '/fiveGADevice.svg',
    );
    scene.value.addImage(
        '05',
        '/plane.svg',
    );
    scene.value.addImage(
        '06',
        '/boat.svg',
    );
    scene.value.on('loaded', () => {
        createControlAreaLayer()
        weatherMap()
        mounted.value = true
        if (mapType.value == 'satellite') {
            //     createSatelliteMap()
            scene.value?.map?.add(new (window as any).AMap.TileLayer.Satellite());
        }
        if (deviceList.value?.length) {
            createDeviceLayer()
            let [lng, lat] = (deviceList.value as any)[0]?.point?.split(',')
            let radius = (deviceList.value as any)[0]?.radius
            let status = (deviceList.value as any)[0]?.status
            let id = (deviceList.value as any)[0]?.id
            scanPanTo([Number(lng), Number(lat)], false, radius, status, id)
        }
    });
}
const weatherMap = () => {
    (window as any).AMap.plugin(['AMap.Weather', 'AMap.CitySearch', 'AMap.Geocoder'], () => {
        let amapWeather: any
        let amapCity: any
        amapWeather = new (window as any).AMap.Weather()
        amapCity = new (window as any).AMap.CitySearch()

        // 使用Geocoder解析地名对应的天气信息
        const getLive = (location: any) => {
            return new Promise((resolve, reject) => {
                amapWeather.getLive(location, (_: any, result: any) => {
                    if (result) {
                        resolve(result || {})
                    } else {
                        reject('')
                    }
                })
            })
        }
        // 使用定位当前城市
        const getCity = () => {
            return new Promise((resolve, reject) => {
                amapCity.getLocalCity((_: any, result: any) => {
                    if (result) {
                        resolve(result || {})
                    } else {
                        reject('')
                    }
                })
            })
        }
        // 传入地名，解析对应的天气，切记过滤掉掉0,0
        const getData = async () => {
            const city: any = await getCity()
            const res: any = await getLive(city.city)
            temp.weather = {
                ...res
            }
        }
        getData()
    })
};
let popup: any = null
const emit = defineEmits(['showDetail', 'showDevice'])
// // 2维无人机定位操作
const createFlatSpectPointLayer = () => {
    // let popup:any = null
    if (!local.showSetting.exploration.includes('spect')) return;
    if (!spectList.value?.length) return;
    spectPointLayer.value = new PointLayer({
        zIndex: 5,
    }).source(
        spectList.value?.filter((item: any) => item.uavBasic.id !== deviceSn.value).map((item: any, index: any) => {
            return {
                ...item,
                lng: item.uavLocation.lon,
                lat: item.uavLocation.lat,
                index,
                id: index
            }
        })
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                // zoomOffset: 1,
            },
        })
        .shape(local.reserveType === 0 ? '02' : '03')
        .size(20);
    scene.value.addLayer(spectPointLayer.value)
    spectPointLayer.value.on('click', (e: any) => {
        emit('showDetail', e.feature.uavBasic.id)
    });
    spectPointLayer.value.on('mouseenter', (e: any) => {
        let html1 = `<span>${e.feature.whiteUav.uavNum ? e.feature.whiteUav.uavNum : '暂未登记号牌'} </span>`
        let html2 = `<span style="font-size: 11.5px;">${e.feature.objectId ? e.feature.objectId : '-'} </span>`
        if (e.feature.whiteUav.suffix == '警用') {
            html1 += `<span style="color:${e.feature.whiteUav.color}">警用</span>`
        } else if (e.feature.whiteUav.suffix == '单位') {
            html1 += `<span style="color:${e.feature.whiteUav.color}">单位</span>`
        } else {
            html1 += `<span style="color:${e.feature.whiteUav.color}">个人</span>`
        }
        popup = new Popup({
            html: local.reserveType === 0 ? html1 : html2,
            lngLat: {
                lng: e.lngLat.lng,
                lat: e.lngLat.lat,
            },
        });
        scene.value.addPopup(popup);
    });
    spectPointLayer.value.on('mouseout', (_e: any) => {
        popup && scene.value?.removePopup(popup);
        popup = null
    });
}
// 3维无人机定位
let spectPointLayer3D: any
const createSpectPointLayer = () => {
    // let popup:any = null
    spectPointLayer3D && scene.value?.removeLayer(spectPointLayer3D)
    if (!local.showSetting.exploration.includes('spect')) return;
    const create = (item: any) => {
        // 无人机定位
        spectPointLayer3D = new PointLayer({
            zIndex: 10,
        })
            .source({
                type: "FeatureCollection",
                crs: {
                    type: "name",
                    properties: {
                        name: "urn:ogc:def:crs:OGC:1.3:CRS84"
                    }
                },
                features: [
                    {
                        "type": "Feature",
                        "properties": {
                            "mag": 2.3,
                            "time": item.createTime,
                            "felt": null,
                            "tsunami": 0,
                            "height": item.uavLocation.height,
                            "whiteUav": {
                                ...item.whiteUav
                            },
                            "uavBasic": {
                                ...item.uavBasic
                            },
                            "uavLocation": {
                                ...item.uavLocation
                            }
                        },
                        "geometry": {
                            "type": "Point",
                            "coordinates": [item?.uavLocation?.lon, item?.uavLocation?.lat]
                        }
                    }
                ]
            })
            .shape(local.reserveType == 0 ? '02' : '03')
            .size(20)
            .style({
                raisingHeight: (item?.height) * 8,
                heightfixed: true
            })
        scene.value.addLayer(spectPointLayer3D);
        spectPointLayer3D.on('click', (e: any) => {
            emit('showDetail', e?.feature?.properties?.uavBasic?.id)
        });
        spectPointLayer3D.on('mouseenter', (e: any) => {
            let html1 = `<span>${e?.feature?.properties?.whiteUav?.uavNum ? e.feature.properties.whiteUav.uavNum : '暂未登记号牌'} </span>`
            let html2 = `<span style="font-size: 11.5px;">${e?.feature?.properties?.uavBasic?.id ? e.feature.properties.uavBasic.id : '-'} </span>`
            if (e.feature.properties.whiteUav.suffix == '警用') {
                html1 += `<span style="color:${e.feature.properties.whiteUav.color}">警用</span>`
            } else if (e.feature.properties.whiteUav.suffix == '单位') {
                html1 += `<span style="color:${e.feature.properties.whiteUav.color}">单位</span>`
            } else {
                html1 += `<span style="color:${e.feature.properties.whiteUav.color}">个人</span>`
            }
            popup = new Popup({
                html: local.reserveType === 0 ? html1 : html2,
                lngLat: {
                    lng: e.feature.properties.uavLocation.lon,
                    lat: e.feature.properties.uavLocation.lat,
                },
            });
            scene.value.addPopup(popup);
        });
        spectPointLayer3D.on('mouseout', (_e: any) => {
            popup && scene.value?.removePopup(popup);
            popup = null
        });
    }
    let obj = spectList.value.find((item: any) => item?.uavBasic?.id == deviceSn.value)
    obj && create(obj)
}
// let spectPointLayerList: any = spectData.map(item => createSpectPointLayer(item))
// console.log(spectPointLayerList)
// 2维无人机轨迹
// const createTrackLayer = () => {
//     console.log(trackList.value)
//     if (!local.showSetting.track) return;
//     trackPointLayer.value = new LineLayer({
//         zIndex: 3,
//     }).source(
//         // [{ lng: 120.5210, lat: 30.40039, }]
//         [{
//             track: trackList.value,
//         }]
//         , {
//             parser: {
//                 type: 'json',
//                 coordinates: 'track',
//             },
//         })
//         .shape('line')
//         .size(2)
//         .color('#00BFFF')
//         .animate({
//             interval: 1, // 间隔
//             duration: 1, // 持续时间，延时
//             trailLength: 2, // 流线长度
//         })
//         .style({
//             speed: 2,
//         });
//     scene.value.addLayer(trackPointLayer.value)
//     // 获取数组中最后一条数据
//     if (!trackList?.value?.length) return;
//     let lastItem = trackList?.value[trackList?.value?.length - 1];
//     scene.value && scene.value?.setCenter(lastItem, true);
// }

// 3维无人机轨迹
const createTrackLayer = () => {
    if (!local.showSetting.track) return;
    // console.log(trackList.value)
    // 3D轨迹气泡空间数据处理
    const trackPointSpaceData = {
        features: trackList.value.map((item: any) => {
            return {
                type: "Feature",
                properties: {
                    id: item.uavBasic.id,
                    mag: 2.3,
                    time: 1507425650893,
                    felt: null,
                    tsunami: 0,
                    color: '#5B8FF9',
                },
                geometry: {
                    type: "Point",
                    coordinates: [
                        Number(item.uavLocation.lon), Number(item.uavLocation.lat), Number(item.uavLocation.height)
                    ]
                }
            }
        }),
        type: "FeatureCollection",
        crs: {
            type: "name",
            properties: {
                name: "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        }
    }
    // 3D轨迹数据处理
    const trackPointData = {
        type: "FeatureCollection",
        name: "tw",
        crs: {
            type: "name",
            properties: {
                name: "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        features: [
            {
                type: "Feature",
                properties: {},
                geometry: {
                    type: "LineString",
                    coordinates: trackList.value.map((item: any) => [
                        Number(item.uavLocation.lon), Number(item.uavLocation.lat), Number(item.uavLocation.height)
                    ])
                }
            }
        ]
    }
    // 3D轨迹气泡空间
    trackPointSpaceLayer.value = new PointLayer({})
        .source(trackPointSpaceData)
        .shape('simple')
        // .active(true)
        .size(30)
        .color('#5B8FF9')
        .animate({
            interval: 1, // 间隔
            duration: 1, // 持续时间，延时
            trailLength: 2, // 流线长度
        })
        .style({
            opacity: 0.6,
            strokeWidth: 2,
            stroke: '#38FFF2'
        });
    scene.value.addLayer(trackPointSpaceLayer.value)
    // 3D轨迹
    trackPointLayer.value = new LineLayer({})
        .source(trackPointData)
        .size(3)
        .shape('line')
        // .active(true)
        .style({
            vertexHeightScale: 8,
            speed: 2,
        })
        .animate({
            interval: 1, // 间隔
            duration: 1, // 持续时间，延时
            trailLength: 2, // 流线长度
        })
        .color('#FFFC38');
    scene.value.addLayer(trackPointLayer.value)

    // 获取数组中最后一条数据
    if (!trackList?.value?.length) return;
    let lastItem: any = trackList?.value[trackList?.value?.length - 1];
    scene.value && scene.value?.setCenter([lastItem.uavLocation.lon, lastItem.uavLocation.lat], true);
}

//无人机操作人员定位操作
const createOperatorPointLayer = () => {
    if (!local.showSetting.operator) return;
    operatorPointLayer.value = new PointLayer({
        zIndex: 2,
    }).source(
        // [{ lng: 120.5210, lat: 30.40039, }]
        spectList.value?.map((item: any) => {
            return {
                lng: item.uavOperatorInfo.lon,
                lat: item.uavOperatorInfo.lat
            }
        })
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                zoomOffset: 1,
                // extent: [-180, -85.051129, 179, 85.051129],
            },
        })
        .shape('01')
        .size(20);
    scene.value.addLayer(operatorPointLayer.value)
}
//无人机和飞手之间一条红线连接
const createCorrelationLayer = () => {
    if (!local.showSetting.correlation) return;
    if (!spectList.value.length) return;
    // 将两个点放入一个数组中
    // let correlation = [latLngPointSpect, latLngPointOperator];
    correlationPointLayer.value = new LineLayer({
        zIndex: 3,
    }).source(
        spectList.value.filter((item: any) => ((item.uavLocation.lon) && (item.uavLocation.lat) && (item.uavOperatorInfo.lon) && (item.uavOperatorInfo.lat))).map((item: any) => {
            return {
                ...item,
                correlation: [
                    [item.uavLocation?.lon, item.uavLocation?.lat],
                    [item.uavOperatorInfo?.lon, item.uavOperatorInfo?.lat]
                ]
            }
        })
        , {
            parser: {
                type: 'json',
                coordinates: 'correlation',
            },
        })
        .shape('line')
        .size(2)
        .color('#FF0000');
    scene.value.addLayer(correlationPointLayer.value)
}
// 设备范围
const createDeviceRangeLayer = (lngLat: any, radius = 1000, status = 0, id?: any) => {
    if (!lngLat?.length) return;
    if (!local.showSetting.range) return;
    lastScanPosition.value = lngLat
    deviceRangeRadius.value = radius
    deviceScanStatus.value = status
    storedDeviceId.value = id
    const statusStyle = {
        '0': '#666666',
        '1': '#1990ff',
        '2': '#666666',
        '3': '#ff0000'
    } as any
    let circle1 = useCreateGeoJSONCircle({
        longitude: lngLat[0],
        latitude: lngLat[1]
    }, radius)
    let circle2 = useCreateGeoJSONCircle({
        longitude: lngLat[0],
        latitude: lngLat[1]
    }, radius / 2)
    const overwriteStyle = {
        color: statusStyle[status]
    };

    deviceRangeLayer.value = new DrawCircle(scene.value, {
        initialData: [circle1, circle2],
        editable: false,
        style: {
            point: {
                normal: overwriteStyle,
                hover: overwriteStyle,
                active: overwriteStyle,
            },
            line: {
                normal: overwriteStyle,
                hover: overwriteStyle,
                active: overwriteStyle,
            },
            polygon: {
                normal: overwriteStyle,
                hover: overwriteStyle,
                active: overwriteStyle,
            },
            midPoint: {
                normal: overwriteStyle,
            },
            dashLine: {
                normal: overwriteStyle,
            },
            text: {
                normal: overwriteStyle,
                active: overwriteStyle,
            },
        },
    });
}
//设备扫描定位操作
const createDeviceScanLayer = (lngLat: any, status = 0, id?: any) => {
    if (!local.showSetting.scan) return;
    if (!lngLat?.length) return;
    lastScanPosition.value = lngLat
    deviceScanStatus.value = status
    storedDeviceId.value = id
    let [lng, lat] = lngLat
    const statusStyle = {
        '0': '#666666',
        '1': '#1990ff',
        '2': '#1990ff',
        '3': '#ff0000'
    } as any
    deviceScanLayer.value = new PointLayer({
        zIndex: 5,
    }).source([{
        lng: Number(lng),
        lat: Number(lat)
    }]
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                zoomOffset: 1,
                updateStrategy: 'realtime'
            },
        })
        .shape('radar')
        .size(200)
        .color((status == 3) ?
            '#ff000' : ((statusStyle[status]) || '#1990ff'))
        .style({
            speed: 2,
        })
        .animate((status == 0) ? false : true);

    scene.value.addLayer(deviceScanLayer.value)
}
//设备定位操作
let devicePopup: any = null
const createDeviceLayer = () => {
    if (!local.showSetting.device) return;
    let list = deviceList.value?.map((item: any) => {
        let [lng, lat] = item.point?.split(',')
        return {
            ...item,
            lng: Number(lng),
            lat: Number(lat)
        }
    })
    deviceLayer.value = new PointLayer({
        zIndex: 8,
    }).source(list
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                zoomOffset: 1,
                updateStrategy: 'realtime'
            },
        })
        .shape(local.reserveType === 0 ? '00' : '04')
        .size(40);
    scene.value.addLayer(deviceLayer.value)
    deviceLayer.value.on('click', (e: any) => {
        emit('showDevice', e.feature.id)
        let arr = e.feature.point.split(',')
        scanPanTo(arr.map((item: any) => Number(item)), false, e.feature.radius, e.feature.status, e.feature.id)
    });
    deviceLayer.value.on('mouseenter', (e: any) => {
        let html1 = `<span>${e.feature?.address}</span>`
        let html2 = `<span>${e.feature?.name}</span>`
        devicePopup = new Popup({
            html: local.reserveType === 0 ? html1 : html2,
            lngLat: {
                lng: e.lngLat.lng,
                lat: e.lngLat.lat,
            },
        });
        scene.value.addPopup(devicePopup);
    });
    deviceLayer.value.on('mouseout', (_e: any) => {
        devicePopup && scene.value?.removePopup(devicePopup);
        devicePopup = null
    });
}
//飞机定位操作
let planePopup: any = null
const createPlanePointLayer = () => {
    if (!local.showSetting.exploration.includes('plane')) return;
    if (!planeList.value?.length) return;
    planePointLayer.value = new PointLayer({
        zIndex: 8,
    }).source(
        planeList.value?.map((item: any, index: any) => {
            return {
                ...item,
                lng: item.longitude,
                lat: item.latitude,
                index,
                id: index
            }
        })
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                // zoomOffset: 1,
            },
        })
        .shape('05')
        .size(20);
    scene.value.addLayer(planePointLayer.value)
    planePointLayer.value.on('mouseenter', (e: any) => {
        planePopup = new Popup({
            html: `<div>
            <p>飞机ID:${e?.feature?.callSign ? e?.feature?.callSign : '-'}</p>
            <p>经纬度:${e?.feature?.longitude.toFixed(4)}，${e?.feature?.latitude.toFixed(4)}</p>
            </div>`,
            lngLat: {
                lng: e.feature.longitude,
                lat: e.feature.latitude,
            },
        });
        scene.value.addPopup(planePopup);
    });
    planePointLayer.value.on('mouseout', (_e: any) => {
        planePopup && scene.value?.removePopup(planePopup);
        planePopup = null
    });
}
let boatPopup: any = null
//船舶定位操作
const createBoatPointLayer = () => {
    if (!local.showSetting.exploration.includes('boat')) return;
    if (!boatList.value?.length) return;
    boatPointLayer.value = new PointLayer({
        zIndex: 8,
    }).source(
        boatList.value?.map((item: any, index: any) => {
            return {
                ...item,
                lng: item.longitude,
                lat: item.latitude,
                index,
                id: index
            }
        })
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                // zoomOffset: 1,
            },
        })
        .shape('06')
        .size(20);
    scene.value.addLayer(boatPointLayer.value)
    boatPointLayer.value.on('mouseenter', (e: any) => {
        boatPopup = new Popup({
            html: `<div>
            <p>船舶ID:${e?.feature?.userID}</p>
            <p>经纬度:${e?.feature?.longitude.toFixed(4)}，${e?.feature?.latitude.toFixed(4)}</p>
            </div>`,
            lngLat: {
                lng: e.feature.longitude,
                lat: e.feature.latitude,
            },
        });
        scene.value.addPopup(boatPopup);
    });
    boatPointLayer.value.on('mouseout', (_e: any) => {
        boatPopup && scene.value?.removePopup(boatPopup);
        boatPopup = null
    });
}


// *风控管理区域
const createControlAreaLayer = () => {
    if (!local.showSetting.controlArea) return;
    // controlAreaLayer.value = new LineLayer({
    //     zIndex: 10
    // }).source(controlAreaList.value?.map((item: any) => {
    //     item.coordinates = item.points?.map((subItem: any) => {
    //         return [subItem.lng, subItem.lat]
    //     })
    //     return item
    // }), {
    //     parser: {
    //         type: 'json',
    //         coordinates: 'coordinates'
    //     },
    // }).size(1)
    //     .color('color')
    // scene.value.addLayer(controlAreaLayer.value);
    // console.log(list.value)
    // const data = {
    //     features: controlAreaList.value.map((item: any) => {
    //         return {
    //             type: "Feature",
    //             properties: {
    //                 color: item.color,
    //             },
    //             geometry: {
    //                 type: "Polygon",
    //                 coordinates: [item.points?.map((subItem: any) => {
    //                     return [Number(subItem.lng?.toFixed(6)), Number(subItem.lat?.toFixed(6))]
    //                 })]
    //             }
    //         }
    //     }),
    //     type: "FeatureCollection"
    // }
    // controlAreaLayer.value = new PolygonLayer({})
    //     .source(data)
    //     .color('color', (color) => {
    //         // console.log(color)
    //         return color + '30' //加透明度
    //     })
    //     .shape('fill')
    //     .active(true);
    // controlAreaLayer2.value = new LineLayer({
    //     zIndex: 2,
    // })
    //     .source(data)
    //     .color('color')
    //     .active(true)
    //     .size(1)
    //     .style({
    //         lineType: 'solid'
    //     });
    // scene.value.addLayer(controlAreaLayer.value);
    // scene.value.addLayer(controlAreaLayer2.value);
    const data = {
        features: controlAreaList.value.filter((item: any) =>(item.status === 0 || item.status === 3) && item.points?.length)?.map((item: any) => {
            return {
                type: "Feature",
                properties: {
                    color: item.color,
                    height: item.limitHeight || 5
                },
                geometry: {
                    type: "Polygon",
                    coordinates: [item.points?.map((subItem: any) => {
                        return [Number(subItem.lng?.toFixed(6)), Number(subItem.lat?.toFixed(6))]
                    })]
                }
            }
        }),
        type: "FeatureCollection"
    }
    controlAreaLayer.value = new LineLayer({})
        .source(data)
        .size('height')
        .shape('wall')
        .color('color', (color) => {
            return color + '80'
        })
        .style({
            opacity: 1,
        });
    controlAreaLayer2.value = new LineLayer({})
        .source(data)
        .size(1)
        .color('color', (color) => {
            return color + '80'
        })
        .style({
            opacity: 1,
        });
    scene.value.addLayer(controlAreaLayer.value);
    scene.value.addLayer(controlAreaLayer2.value);
}
// 地图控件部分
// 测距
const distance = () => {
    const drawLine = new DrawLine(scene.value, {
        distanceOptions: {},
        style: {
            point: {
                options: {
                    zIndex: 10,
                }
            },
            line: {
                options: {
                    zIndex: 10,
                }
            }
        }
    });
    drawLine.enable();
}
// 回到中心点
const backCenter = () => {
    const center = [121.245800, 31.394559];
    scene.value.panTo(center);
}
// 地图放大
const magnify = () => {
    scene.value.zoomIn();
}
// 地图缩小
const lessen = () => {
    scene.value.zoomOut();
}
//无人机，飞手，设备跟踪操作
const panTo = (lngLat: any) => {
    scene.value && scene.value?.setCenter([Number(lngLat[0].toFixed(6)), Number(lngLat[1].toFixed(6))], true);
    // scene.value && scene.value?.panTo([Number(lngLat[0].toFixed(6)),Number(lngLat[1].toFixed(6))]);
}
//雷达跟踪操作
const scanPanTo = (lngLat: any, isCenter = false, radius = 1000, status = 0, id?: any) => {
    if (!mounted.value) return
    if (scene.value) {
        deviceScanLayer.value && scene.value?.removeLayer(deviceScanLayer.value);
        deviceScanLayer.value = null
        // deviceRangeLayer.value && scene.value?.removeLayer(deviceRangeLayer.value);
        deviceRangeLayer.value?.destroy()
        deviceRangeLayer.value = null
    }
    if (!isCenter) {
        panTo(lngLat)
        // scene.value && scene.value?.setZoomAndCenter(5,lngLat)
    }
    createDeviceScanLayer(lngLat, status, id)
    createDeviceRangeLayer(lngLat, radius, status, id)
}
onMounted(() => {
    nextTick(() => {
        init()
    })
})
const destroy = () => {
    scene.value && scene.value?.destroy();
    scene.value = null
}
onBeforeUnmount(() => {
    destroy()
})
defineExpose({
    distance,
    backCenter,
    magnify,
    lessen,
    panTo,
    scanPanTo
})
useWatch(mapType, () => {
    destroy()
    mounted.value = false
    init()
})
// 飞机
useWatch(planeList, (val: any) => {
    if (!mounted.value) return
    if (scene.value) {
        planePointLayer.value && scene.value?.removeLayer(planePointLayer.value);
        planePointLayer.value = null
    }
    if (!val?.length) return;
    createPlanePointLayer()
})
// 船舶
useWatch(boatList, (val: any) => {
    if (!mounted.value) return
    if (scene.value) {
        boatPointLayer.value && scene.value?.removeLayer(boatPointLayer.value);
        boatPointLayer.value = null
    }
    if (!val?.length) return;
    createBoatPointLayer()
})
// 无人机，飞手及红线
useWatch(spectList, (val: any) => {
    if (!mounted.value) return
    if (scene.value) {
        spectPointLayer.value && scene.value?.removeLayer(spectPointLayer.value);
        spectPointLayer.value = null
        operatorPointLayer.value && scene.value?.removeLayer(operatorPointLayer.value);
        operatorPointLayer.value = null
        correlationPointLayer.value && scene.value?.removeLayer(correlationPointLayer.value);
        correlationPointLayer.value = null
    }
    if (!val?.length) return;
    createFlatSpectPointLayer()
    createSpectPointLayer()
    createOperatorPointLayer()
    createCorrelationLayer()
})
// 跟踪
useWatch(deviceSn, () => {
    if (!mounted.value) return
    if (scene.value) {
        spectPointLayer.value && scene.value?.removeLayer(spectPointLayer.value);
        spectPointLayer.value = null
    }
    createFlatSpectPointLayer()
    createSpectPointLayer()
})
//轨迹
useWatch(trackList, (val: any) => {
    if (!mounted.value) return
    if (scene.value) {
        trackPointLayer.value && scene.value?.removeLayer(trackPointLayer.value);
        trackPointLayer.value = null
        trackPointSpaceLayer.value && scene.value?.removeLayer(trackPointSpaceLayer.value);
        trackPointSpaceLayer.value = null
    }
    if (!val?.length) return;
    createTrackLayer()
})
// 设备，范围，扫描
useWatch(deviceList, (val: any) => {
    if (!mounted.value) return
    if (scene.value) {
        deviceLayer.value && scene.value?.removeLayer(deviceLayer.value);
        deviceLayer.value = null
        deviceScanLayer.value && scene.value?.removeLayer(deviceScanLayer.value);
        deviceScanLayer.value = null
        deviceRangeLayer.value && scene.value?.removeLayer(deviceRangeLayer.value);
        deviceRangeLayer.value = null
    }
    if (!val?.length) return;
    createDeviceLayer()
    let device: any = val.find((i: any) => i.id == storedDeviceId.value)
    if (!device && storedDeviceId.value) return
    let arr = device?.point.split(',').map((item: any) => Number(item))
    createDeviceScanLayer(arr, device?.status, storedDeviceId.value)
    createDeviceRangeLayer(arr, device?.radius, device?.status, storedDeviceId.value)

})
// 侦测管控区域范围
useWatch(controlAreaList, (val: any) => {
    if (!mounted.value) return
    if (scene.value) {
        controlAreaLayer.value && scene.value?.removeLayer(controlAreaLayer.value);
        controlAreaLayer.value = null
        controlAreaLayer2.value && scene.value?.removeLayer(controlAreaLayer2.value);
        controlAreaLayer2.value = null
    }
    if (!val?.length) return;
    createControlAreaLayer()
})
//监听配置展示隐藏
useWatch(() => JSON.stringify(local.showSetting), (newValue: any, oldValue: any) => {
    newValue = JSON.parse(newValue)
    oldValue = JSON.parse(oldValue)
    //设备
    if (newValue.device != oldValue.device) {
        deviceLayer.value && scene.value?.removeLayer(deviceLayer.value);
        deviceLayer.value = null
        createDeviceLayer()
    }
    //管控区域
    if (newValue.controlArea != oldValue.controlArea) {
        controlAreaLayer.value && scene.value?.removeLayer(controlAreaLayer.value);
        controlAreaLayer.value = null
        controlAreaLayer2.value && scene.value?.removeLayer(controlAreaLayer2.value);
        controlAreaLayer2.value = null
        createControlAreaLayer()
    }
    //雷达扫描
    if (newValue.scan != oldValue.scan) {
        deviceScanLayer.value && scene.value?.removeLayer(deviceScanLayer.value);
        deviceScanLayer.value = null
        scanPanTo(lastScanPosition.value, true, deviceRangeRadius.value, deviceScanStatus.value)
    }
    //范围
    if (newValue.range != oldValue.range) {
        deviceRangeLayer.value && scene.value?.removeLayer(deviceRangeLayer.value);
        deviceRangeLayer.value = null
        scanPanTo(lastScanPosition.value, true, deviceRangeRadius.value, deviceScanStatus.value)
    }
    //飞手
    if (newValue.operator != oldValue.operator) {
        operatorPointLayer.value && scene.value?.removeLayer(operatorPointLayer.value);
        operatorPointLayer.value = null
        createOperatorPointLayer()
    }
    if (newValue.exploration?.length != oldValue.exploration?.length) {
        planePointLayer.value && scene.value?.removeLayer(planePointLayer.value);
        boatPointLayer.value && scene.value?.removeLayer(boatPointLayer.value);
        spectPointLayer.value && scene.value?.removeLayer(spectPointLayer.value);
        planePointLayer.value = null
        boatPointLayer.value = null
        spectPointLayer.value = null
        //飞机
        if (newValue.exploration.includes('plane')) {
            createPlanePointLayer()
        }
        //船舶
        if (newValue.exploration.includes('boat')) {
            createBoatPointLayer()
        }
        //无人机
        if (newValue.exploration.includes('spect')) {
            createFlatSpectPointLayer()
            createSpectPointLayer()
        }
    }
    // //无人机
    // if (newValue.spect != oldValue.spect) {
    //     spectPointLayer.value && scene.value?.removeLayer(spectPointLayer.value);
    //     spectPointLayer.value = null
    //     createFlatSpectPointLayer()
    //     createSpectPointLayer()
    // }
    //无人机轨迹
    if (newValue.track != oldValue.track) {
        trackPointLayer.value && scene.value?.removeLayer(trackPointLayer.value);
        trackPointLayer.value = null
        trackPointSpaceLayer.value && scene.value?.removeLayer(trackPointSpaceLayer.value);
        trackPointSpaceLayer.value = null
        createTrackLayer()
    }
    //无人机与飞手之间的红线
    if (newValue.correlation != oldValue.correlation) {
        correlationPointLayer.value && scene.value?.removeLayer(correlationPointLayer.value);
        correlationPointLayer.value = null
        createCorrelationLayer()
    }
})
</script>
<style scoped lang="less">
#map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;

    :deep(.l7-control-container) {
        display: none;
    }
}
</style>